<script setup>
import { getOrderCommonLotnumber } from '@/api/orderManagement/common'
import { ElInput, ElMessage, ElTag, ElText } from 'element-plus'

const tableData = ref([])
const tableRef = ref()

const rowKey = row => {
  return props.mode === 'select' ? row.lotnumberid : row.index
}

const tableColumn = ref([
  {
    label: '数量',
    prop: 'quantity',
    width: 140,
    render: row =>
      h(ElInput, {
        modelValue: row.quantity,
        'onUpdate:modelValue': value => (row.quantity = value),
        type: 'number'
      })
  },

  { label: '产品编号', prop: 'prodid', width: 140 },
  { label: '仓库', prop: 'warehouseid', width: 100 },
  { label: '批号', prop: 'lotnumberid', width: 100 },
  { label: '批号数量', prop: 'phsl', width: 100 }
])

const props = defineProps({
  modelValue: {
    type: Boolean
  },
  rowData: {
    type: Object,
    required: true
  },
  disableds: {
    type: Array,
    default: () => []
  },
  mode: {
    type: String,
    default: 'select'
  }
})

const emits = defineEmits(['update:modelValue', 'selected'])

const selectedCount = computed(() => {
  let length = 0
  if (tableRef.value) {
    length = tableRef.value?.tableRef.getSelectionRows().length
  }
  return length
})

const residueQuantity = computed(() => {
  if (props.rowData) {
    return (
      props.rowData.quantity -
      tableData.value.reduce((curr, prev) => (curr += Number(prev.quantity)), 0)
    )
  } else {
    return 0
  }
})

const loadData = async () => {
  const { prodid } = props.rowData
  if (!prodid) {
    ElMessage.warning('未选择产品！')
    emits('update:modelValue', false)
    return
  }

  if (props.mode !== 'select') {
    tableColumn.value = [
      {
        label: '批号',
        prop: 'lotnumberid',
        width: 140,
        render: row =>
          h(ElInput, {
            modelValue: row.lotnumberid,
            'onUpdate:modelValue': value => {
              console.log(value)
              row.lotnumberid = value
            }
          })
      },
      {
        label: '数量',
        prop: 'quantity',
        width: 140,
        render: row =>
          h(ElInput, {
            modelValue: row.quantity,
            'onUpdate:modelValue': value => {
              row.quantity = value
              row.jbquantity = value
            },
            type: 'number'
          })
      },
      { label: '单位', prop: 'unit', width: 140 },
      {
        label: '基本数量',
        prop: 'jbquantity',
        width: 140,
        render: row =>
          h(ElInput, {
            modelValue: row.jbquantity,
            'onUpdate:modelValue': value => (row.jbquantity = value),
            type: 'number'
          })
      }
    ]

    tableData.value = props.rowData.batchusedList

    tableRef.value?.tableRef.clearSelection()
    props.rowData.batchusedList.forEach(item => {
      tableRef.value?.tableRef.toggleRowSelection(item)
    })
    return
  }
  const { data } = await getOrderCommonLotnumber({ prodid })
  tableRef.value?.tableRef.clearSelection()
  tableData.value = data.map(item => {
    item.quantity = 0

    const index = props.rowData.batchusedList.findIndex(sub => sub.lotnumberid === item.lotnumberid)
    if (index !== -1) {
      item.quantity = props.rowData.batchusedList[index].quantity
      tableRef.value?.tableRef.toggleRowSelection(item)
    }
    return item
  })
}

const rowSelection = selected => {
  selected.map(item => {
    item.quantity = item.quantity ? item.quantity : props.rowData.quantity
    return item
  })
}

const addRow = () => {
  const index = tableData.value.length > 0 ? tableData.value.length : 0
  tableData.value.push({
    lotnumberid: '',
    quantity: 0,
    unit: props.rowData.unit,
    jbquantity: '',
    index,
    prodid: props.rowData.prodid
  })
}

const confirm = () => {
  const selected = tableRef.value?.tableRef.getSelectionRows()
  if (selected.length === 0) {
    ElMessage.warning('请选择产品')
  } else {
    const sum = selected.reduce((curr, prev) => (curr += Number(prev.quantity)), 0)
    if (sum > props.rowData.quantity) {
      ElMessage.warning('批号选择数量超出')
      return
    }
    props.rowData.batchusedList = selected
    emits('selected', selected)
    close()
  }
}

const close = () => {
  tableRef.value?.tableRef.clearSelection()
  tableData.value = []
  emits('update:modelValue', false)
}
</script>

<template>
  <el-dialog
    class="order-dialog"
    width="70%"
    :modelValue="$props.modelValue"
    :title="`${$props.rowData.prodid}批号信息`"
    draggable
    @open="loadData"
    @close="close"
  >
    <ps-table
      :data="tableData"
      :tableColumn="tableColumn"
      :row-key="rowKey"
      ref="tableRef"
      class="ps_table_edit"
      @selection-change="rowSelection"
      :pageSize="10"
    >
      <template #tools>
        <el-row align="middle">
          <el-col :span="2" v-if="$props.mode !== 'select'">
            <el-button size="small" type="primary" @click="addRow">新增</el-button>
          </el-col>

          <el-col :span="3">
            <span>
              <span>已选择</span>
              <span class="selectedCount">{{ selectedCount }}</span>
              <span>条</span>
            </span>
          </el-col>

          <el-col :span="3">
            <span>
              <span>剩余数量</span>
              <span class="selectedCount">{{ residueQuantity }}</span>
            </span>
          </el-col>
        </el-row>
      </template>

      <template #header>
        <el-table-column type="selection" width="60" reserve-selection fixed />
      </template>
    </ps-table>

    <template #footer>
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="close">关闭</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.selectedCount {
  color: var(--el-color-primary);
}
</style>
